package com.cms.staticpage.impl;

import static com.cms.Constants.UTF8;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.cms.dao.PageTemplatesDAOImpl;
import com.cms.entity.PageTemplates;
import com.cms.staticpage.StaticPageSvc;
import com.cms.web.FrontUtils;
import com.common.web.RealPathResolver;
import com.core.dao.ProductDAO;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class StaticPageSevImpl implements StaticPageSvc {
	
	@Autowired
	private PageTemplatesDAOImpl templatesDao;
	
	private Logger log = LoggerFactory.getLogger(StaticPageSevImpl.class);
	
	@Override
	public void index() throws IOException, TemplateException {
		long e=System.currentTimeMillis();
	   // productDao.queryForCount();	
		Map<String, Object> data = new HashMap<String, Object>();
		FrontUtils.frontData(data);
		//查询首页对于的模板和生产文件路径
		PageTemplates template=templatesDao.selectByPrimaryKey(1);
		index(template,data);
	}

	@Override
	public void index(PageTemplates templates, Map<String, Object> data) throws IOException,
			TemplateException {
		//生成文件路径，从根目录开始
		String path=resolver.get(templates.getGenerationPath());
		//对于模板路径
		String tpl=templates.getTemplatesPath();
		Assert.notNull(path);
		Assert.notNull(tpl);
		long time = System.currentTimeMillis();
		File f = new File(path);
		File parent = f.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		Writer out = null;
		try {
			// FileWriter不能指定编码确实是个问题，只能用这个代替了。
			out = new OutputStreamWriter(new FileOutputStream(f), UTF8);
			Template template = conf.getTemplate(tpl);
			template.process(data, out);
		} 
		finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
		time = System.currentTimeMillis() - time;
		log.info("首页文件生成静态成功 ：耗时：", time);

	}
	
	
	@Autowired
	private RealPathResolver resolver;
	
	private Configuration conf;
	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer) {
		this.conf = freeMarkerConfigurer.getConfiguration();
	}
}
